<script setup lang="ts">
import {
  getAllPaymentProjectByIdApi,
  isPaidApi,
  paymentApi,
} from '@src/apis/paymentProjectApi.ts'
import { onMounted, onUnmounted, ref } from 'vue'
import {
  ElMessage,
  ElTable,
  genFileId,
  UploadInstance,
  UploadProps,
  UploadRawFile,
} from 'element-plus'
import { Picture as IconPicture } from '@element-plus/icons-vue'
import { getImageUrlByImageName, uploadImageApi } from '@src/apis/imageApi.ts'
import formatDate from '@util/formatDate.ts'
import Pagination from '@src/components/Pagination.vue'
import TokenUtil from '@util/TokenUtil.ts'
import { EnumUserRole } from '@src/enums/EnumUserRole.ts'
import { router } from '@util/RouterUtil.ts'
import useUserStore from '@src/stores/useUserStore.ts'
import { storeToRefs } from 'pinia'
import ImagePreview from '@src/components/ImagePreview.vue'
interface PaymentProject {
  id: number
  title: string
  description: string
  amount: number
  classId: number
  deadLine: Date
  imageName: '测试'
  isPaid: boolean
  isDelete: string
}
// 用户信息
const userStore = useUserStore()
const userInfo = storeToRefs(userStore).userInfo
// 储存全部缴费记录变量
const tableData = ref<PaymentProject[]>([])
// 展示某条缴费记录信息变量
const itemForm = ref({})
// 修改消息表单数据校验变量
const editRuleForm = ref<UploadInstance>()
// 显示展示某条信息表单框变量
const infoVisible = ref(false)
// 项目Id
const paymentProjectId = ref(19)
// 显示缴费对话框
const paymentVisible = ref(false)
// 图片名称
const imageName = ref('')
// 显示缴费图片
const dialogImageUrl = ref('')
// 当前显示的是第几页
const currentPage = ref(1)
// 每页显示多少条
const pageSize = ref(2)
// 总记录条数
const total = ref(0)
// 搜索信息
const text = ref('')
//是否支付过
const isPaidProject = ref(false)
// 钩子函数调用查询函数
onMounted(() => {
  TokenUtil.refresh().then(() => {
    if (userInfo.value.classId === undefined) {
      ElMessage.warning('你还未加入班级,无法缴费。返回首页')
      router.push('/')
      return
    }
    getAllPaymentProjectById(currentPage.value, pageSize.value, text.value)
  })
})
// 得到全部缴费项目
const getAllPaymentProjectById = (page: number, size: number, text: string) => {
  getAllPaymentProjectByIdApi(page, size, text).then(async (res) => {
    tableData.value = res.data.data.records
    total.value = res.data.data.total
  })
}
// 查看用户是否已经交过该费用
const isPaid = (ProjectId: number) => {
  return isPaidApi(ProjectId).then((obj) => {
    return obj.data
  })
}
const handleInfo = (row: PaymentProject) => {
  infoVisible.value = true
  itemForm.value = row
  dialogImageUrl.value = getImageUrlByImageName(row.imageName)
}

const handleSizeChange = (size: number) => {
  pageSize.value = size
  getAllPaymentProjectById(currentPage.value, pageSize.value, text.value)
}
const handleCurrentChange = (page: number) => {
  currentPage.value = page
  getAllPaymentProjectById(currentPage.value, pageSize.value, text.value)
}
const submitPayment = () => {
  if (imageName.value == '') {
    ElMessage.warning('请上传缴费截图')
    return
  }
  payment(paymentProjectId.value, imageName.value)
}
const handlePayment = (row: PaymentProject) => {
  paymentVisible.value = true
  dialogImageUrl.value = getImageUrlByImageName(row.imageName)
  paymentProjectId.value = row.id
}
function payment(paymentProjectId: number, imageName: string) {
  paymentApi(paymentProjectId, imageName).then((obj) => {
    if (obj.data.code == 200) {
      ElMessage.success(obj.data.message)
      submitHandleDialogClose()
      getAllPaymentProjectById(currentPage.value, pageSize.value, text.value)
    } else {
      ElMessage.error(obj.data.message)
    }
  })
}
const infoHandleDialogClose = () => {
  infoVisible.value = false
}
const submitHandleDialogClose = () => {
  paymentVisible.value = false
  imageName.value = ''
}
//添加缴费截图
const submitUploadImage = () => {
  editRuleForm.value!.submit()
}
// 提交缴费截图
const myUpload = (content) => {
  uploadImageApi(content.raw).then((obj) => {
    imageName.value = obj.data
  })
}
const handleExceed: UploadProps['onExceed'] = (files) => {
  editRuleForm.value!.clearFiles()
  const file = files[0] as UploadRawFile
  file.uid = genFileId()
  editRuleForm.value!.handleStart(file)
  submitUploadImage()
}
function isDeadlined(deadLine: string) {
  return new Date().getTime() - new Date(deadLine).getTime() >= 0
}

/**预览图片*/
const imagePreviewProps = ref({
  show: false,
  src: '',
  alt: '',
})
onMounted(() => {
  const previewListener = () => {
    const listener = (e: MouseEvent) => {
      const target = e.target as HTMLElement
      if (target.tagName.toLowerCase() !== 'img') return

      const imgEl = target as HTMLImageElement
      imagePreviewProps.value.src = imgEl.src
      imagePreviewProps.value.alt = imgEl.alt
      imagePreviewProps.value.show = true
    }
    window.addEventListener('click', listener)

    return () => {
      window.removeEventListener('click', listener)
    }
  }
  const removePreviewListener = previewListener()
  onUnmounted(() => {
    removePreviewListener()
  })
})
</script>

<template>
  <div>
    <h2><el-text>缴纳班费</el-text></h2>
    <!--  展示缴费项目-->
    <el-table
      height="650"
      ref="singleTableRef"
      :data="tableData"
      highlight-current-row
      style="width: 100%"
    >
      <el-table-column type="index" label="序号" width="80" />
      <el-table-column property="title" label="项目标题" />
      <el-table-column property="amount" label="金额" />
      <el-table-column property="deadLine" label="截止时间">
        <template #default="scope">
          {{ formatDate(scope.row.deadLine) }}
        </template>
      </el-table-column>
      <el-table-column label="状态">
        <template #default="scope">
          <el-text type="danger" v-if="scope.row.isDelete == '已删除'">
            已删除
          </el-text>
          <el-text v-else-if="isDeadlined(scope.row.deadLine)">
            已截止
          </el-text>
          <el-text v-else type="success"> 正常 </el-text>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200px">
        <template #default="scope">
          <div class="operation">
            <el-button
              v-if="
                !scope.row.isPaid &&
                scope.row.isDelete != '已删除' &&
                !isDeadlined(scope.row.deadLine)
              "
              type="success"
              @click="handlePayment(scope.row)"
            >
              缴纳班费
            </el-button>
            <el-button @click="handleInfo(scope.row)"> 查看详情 </el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <!--    分页-->
    <Pagination
      :page="currentPage"
      :size="pageSize"
      @size-change="handleSizeChange"
      @page-change="handleCurrentChange"
      :total="total"
    >
    </Pagination>
    <!--    查看缴费项目详情-->
    <div class="paymentRecordInfo">
      <el-dialog
        width="400"
        v-model="infoVisible"
        title="查看缴费信息"
        :before-close="infoHandleDialogClose"
        center
      >
        <el-form label-width="120px">
          <el-form-item label="缴费项目标题">
            <el-input
              v-model="itemForm.title"
              style="width: 210px"
              disabled
            ></el-input>
          </el-form-item>
          <el-form-item label="缴费项目描述">
            <el-input
              type="textarea"
              v-model="itemForm.description"
              style="width: 210px"
              disabled
              class="textArea"
              rows="5"
              resize="none"
              readonly
            ></el-input>
          </el-form-item>
          <el-form-item label="缴费金额(元)">
            <el-input
              v-model="itemForm.amount"
              style="width: 210px"
              disabled
            ></el-input>
          </el-form-item>
          <el-form-item label="截止时间">
            <div class="block">
              <el-date-picker
                v-model="itemForm.deadLine"
                type="datetime"
                placeholder="Pick a Date"
                format="YYYY-MM-DD HH:mm:ss"
                date-format="MMM DD, YYYY"
                time-format="HH:mm"
                disabled
              />
            </div>
          </el-form-item>
          <el-form-item label="缴费二维码">
            <img
              :src="dialogImageUrl"
              style="width: 100px; height: 100px; margin-left: 25px"
              alt=""
            />
          </el-form-item>
        </el-form>
      </el-dialog>
    </div>
    <!--    缴纳班费-->
    <div>
      <el-dialog
        width="600"
        v-model="paymentVisible"
        title="缴费"
        :before-close="submitHandleDialogClose"
        center
      >
        <el-form label-width="250px" center>
          <el-form-item label="缴费二维码">
            <img
              class="paymentImage"
              :src="dialogImageUrl"
              style="width: 100px; height: 100px"
              alt=""
            />
          </el-form-item>
          <el-form-item label="缴费截图（点击图片进行添加）">
            <el-upload
              :show-file-list="false"
              @change="myUpload"
              :auto-upload="false"
            >
              <el-image
                :src="getImageUrlByImageName(imageName)"
                style="width: 100px; height: 100px; margin-left: 25px"
                alt=""
                @click="submitUploadImage"
              >
                <template #error>
                  <div class="image-slot">
                    <el-icon><icon-picture /> </el-icon>
                  </div>
                </template>
              </el-image>
            </el-upload>
          </el-form-item>
          <el-form-item>
            <el-button
              size="default"
              type="warning"
              @click="submitHandleDialogClose"
            >
              取消
            </el-button>
            <el-button size="default" type="success" @click="submitPayment">
              提交
            </el-button>
          </el-form-item>
        </el-form>
      </el-dialog>
    </div>
    <image-preview
      v-model:show="imagePreviewProps.show"
      v-model:src="imagePreviewProps.src"
      v-model:alt="imagePreviewProps.alt"
    />
  </div>
</template>

<style scoped lang="less">
h2 {
  text-align: center;
  .el-text {
    font-size: 2em;
  }
}

.page {
  position: fixed;
  bottom: 5px;
  left: 210px;
}
.paymentImage {
  margin-left: 30px;
}
.operation {
  display: flex;
  justify-content: flex-end;
}
.el-image {
  padding: 0 5px;
  max-width: 300px;
  max-height: 200px;
  width: 100%;
  height: 200px;
}
.image-slot {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  background: var(--el-fill-color-light);
  color: var(--el-text-color-secondary);
  font-size: 30px;
}
.image-slot .el-icon {
  font-size: 30px;
}
</style>
